package models

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type Document struct {
	ID         uint       `gorm:"primaryKey" json:"id"`
	UUID       string     `gorm:"uniqueIndex;not null" json:"uuid"`
	UserID     uint       `gorm:"not null;index" json:"user_id"`
	Title      string     `gorm:"not null;size:255" json:"title"`
	Content    string     `gorm:"type:text;not null" json:"content"`
	Path       string     `gorm:"size:512" json:"path"`
	IsPublic   bool       `json:"is_public"`
	Password   *string    `gorm:"size:255" json:"password,omitempty"`
	Theme      string     `gorm:"default:'github';size:50" json:"theme"`
	Views      int        `gorm:"default:0" json:"views"`
	ExpiresAt  *time.Time `json:"expires_at,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
	UpdatedAt  time.Time  `json:"updated_at"`

	// 关联
	User User `gorm:"foreignKey:UserID" json:"user"`
}

// BeforeCreate 钩子 - 生成 UUID
func (d *Document) BeforeCreate(tx *gorm.DB) error {
	if d.UUID == "" {
		d.UUID = uuid.New().String()
	}
	return nil
}

// IncrementViews 增加浏览量
func (d *Document) IncrementViews() {
	d.Views++
}

// CheckPassword 验证密码
func (d *Document) CheckPassword(password string) bool {
	if d.IsPublic {
		return true
	}
	if d.Password == nil {
		return false
	}
	return *d.Password == password
}

// IsExpired 检查是否过期
func (d *Document) IsExpired() bool {
	if d.ExpiresAt == nil {
		return false
	}
	return d.ExpiresAt.Before(time.Now())
}
